package MyFitnessPlate.TestApplication;
import MyFitnessPlate.DataSet.ParsedLoginInfoDataSet;
import MyFitnessPlate.Handler.LoginInfoHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 
import org.xml.sax.XMLReader;

import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;

public class LogInActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Button button = (Button) findViewById(R.id.log_in_submit_button);
        final Button createAccountButton = (Button) findViewById(R.id.CreateAccountButton);
        
        createAccountButton.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View v){
        		Intent myIntent = new Intent("MyFitnessPlate.TestApplication.CreateAccountActivity.STARTINGPOINT");
				startActivity(myIntent);
        	}
        });
        
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	//Set up user validation variables
            	EditText userEdit = (EditText)findViewById(R.id.login_username);
            	EditText passEdit = (EditText)findViewById(R.id.login_password);
            	
            	//Turn input into strings
            	String userName = userEdit.getText().toString().trim();
            	String userPass = passEdit.getText().toString().trim();
            	
            	try {
            		//Query server and download XML document.
                    URL url = new URL("http://myfitnessplate.com/api/check-user/username/" + userName + "/password/" + userPass + "/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
                    
                    /* Get a SAXParser from the SAXPArserFactory. */
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();
                    /* Get the XMLReader of the SAXParser we created. */
                    XMLReader xr = sp.getXMLReader();
                    /* Create a new ContentHandler and apply it to the XML-Reader*/
                    LoginInfoHandler myLoginInfoHandler = new LoginInfoHandler();
                    xr.setContentHandler(myLoginInfoHandler);
                    /* Parse the xml-data from our URL. */
                    xr.parse(new InputSource(url.openStream()));
                    /* Parsing has finished. */
                    /* Our ExampleHandler now provides the parsed data to us. */
                    ParsedLoginInfoDataSet parsedLoginInfoDataSet = myLoginInfoHandler.getParsedData();
                    
                    //User does not exist
                    if(parsedLoginInfoDataSet.getsuccess().equals("false")){
                    	final AlertDialog alertDialog = new AlertDialog.Builder(LogInActivity.this).create();
                    	alertDialog.setTitle("Error");
                    	alertDialog.setMessage("Username or password is incorrect. Please create an account if new user.");
                    	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    		public void onClick(DialogInterface dialog, int which) {
                    			alertDialog.dismiss();
                    	    }
                    	});
                    	alertDialog.show();
                    }

                    //User exists, so create user object and proceed to home page.
                    if(parsedLoginInfoDataSet.getsuccess().equals("true")){
                    	//Set up user profile by passing successful response.
                    	Log.d("Start Log", "Program Started.");
                    	Bundle b = new Bundle();
                    	b.putString("userName", userName);
                    	b.putString("passWord", userPass);
                    	b.putString("userFirstName", parsedLoginInfoDataSet.getfirstname());
                    	b.putDouble("userHeight", parsedLoginInfoDataSet.getheight());

                    	Intent myIntent = new Intent("MyFitnessPlate.TestApplication.LogInActivity.STARTINGPOINT");
                    	myIntent.putExtras(b);
    					startActivity(myIntent);
    					finish();
                    }
                } catch (MalformedURLException e) {
					e.printStackTrace();
                } catch (IOException e) {
                	e.printStackTrace();
                } catch (SAXParseException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    Exception x = e.getException();
                    ((x == null) ? e : x).printStackTrace();
                } catch (ParserConfigurationException e) {
					e.printStackTrace();
				}
            }
        });
    }
}